/*
 * 
 * 
 * 
 */
package com.hboxs.asl.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hboxs.asl.Filter;
import com.hboxs.asl.Setting;
import com.hboxs.asl.dao.ShippingDao;
import com.hboxs.asl.entity.Order;
import com.hboxs.asl.entity.Shipping;
import com.hboxs.asl.service.ShippingService;
import com.hboxs.asl.util.SettingUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service - 发货单
 */
@Service("shippingServiceImpl")
public class ShippingServiceImpl extends BaseServiceImpl<Shipping, Long> implements ShippingService {

    @Resource(name = "shippingDaoImpl")
    private ShippingDao shippingDao;

    @Resource(name = "shippingDaoImpl")
    public void setBaseDao(ShippingDao shippingDao) {
        super.setBaseDao(shippingDao);
    }

    @Transactional(readOnly = true)
    public Shipping findBySn(String sn) {
        return shippingDao.findBySn(sn);
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    @Cacheable("shipping")
    public Map<String, Object> query(Shipping shipping) {
        Setting setting = SettingUtils.get();
        Map<String, Object> data = new HashMap<String, Object>();
        if (shipping != null && StringUtils.isNotEmpty(setting.getKuaidi100Key()) && StringUtils.isNotEmpty(shipping.getDeliveryCorpCode()) && StringUtils.isNotEmpty(shipping.getTrackingNo())) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                URL url = new URL("http://api.kuaidi100.com/api?id=" + setting.getKuaidi100Key() + "&com=" + shipping.getDeliveryCorpCode() + "&nu=" + shipping.getTrackingNo() + "&show=0&muti=1&order=asc");
                data = mapper.readValue(url, Map.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    @Override
    public Shipping findByOrder(Order order) {
        List<Filter> fs = new ArrayList<>();
        fs.add(Filter.eq("order", order));
        List<Shipping> shippings = shippingDao.findList(null, null, fs, null);
        return shippings.size() == 0 ? null : shippings.get(0);
    }

    @Override
    public String queryByOrder(Order order) {
        String url = "";
        Shipping shipping = findByOrder(order);

        if (shipping != null) {
            url = "https://m.kuaidi100.com/index_all.html?type=" + shipping.getDeliveryCorp() + "&postid=" + shipping.getTrackingNo();
        }

        return url;
    }
}